#coding=utf-8
from uliweb import expose
from uliweb.utils.generic import AddView
import decimal

def __begin__():
    from uliweb import request, redirect
    
    if not request.user:
        return redirect('/login' + '?next=%s' % request.path)

def create_usage_query(url):
    from uliweb.utils.generic import QueryView
    from uliweb.form import SelectField, UnicodeField
    from plugs.ui.jquery.jqcombobox.widgets import JQComboBoxField
    from query.forms import QueryForm
    from uliweb.utils.generic import ReferenceSelectField
    from uliweb.orm import get_model
    from uliweb.form import IntField
    
    System = get_model('system')
    type = SelectField(label='类型', choices=settings.get_var('PARA/HUMAN_TYPE'))
    department = UnicodeField(name='department', label='所属机构')
    name = UnicodeField(name='name', label='姓名')
    login_name = UnicodeField(name='login_name', label='登录名')
    yearmon = IntField(name='yearmon')
#    system = JQComboBoxField(label='系统', url='/systems/query')
    query = None
    if request.user.department == '2':
        if request.user.is_gm:
            query = System.filter(System.c.kfzx==request.user._kfzx_)
        else:
            query = request.user.users_systems.all()
    system = ReferenceSelectField('system', label='系统', query=query)
    
    fields = (('name', name), ('login_name', login_name), ('type', type), 
        'kfzx', ('system', system), ('department', department), ('yearmon',yearmon)) 
    layout = [('kfzx', 'system', 'type'), ('name', 'login_name', 'department')]
    if request.user.department in ('2', '3'):
        layout = [('system', 'type'), ('name', 'login_name', 'department')]
    query = QueryView('resource', ok_url=url, fields=fields, layout=layout, form_cls=QueryForm)
    return query

@expose('/resource/usage')
@expose('/resource/usage/list')
def resource_usage():
    from uliweb.utils.generic import ListView
    from uliweb import orm
    import generic.views as g_views
    from uliweb.core.html import Tag
    
    get_url = g_views.get_url('/resource/usage')

    model = 'resource'

    Department = orm.get_model('department')
    Human = orm.get_model('human')
    Resource = orm.get_model('resource')

    query_view = create_usage_query(url_for(resource_usage))
    c = query_view.run()

    query = None
    condition = Resource.c.delete_flag == False
    if request.user.department == '2':
        if request.user.is_gm:  #如果是开发中心主管，则只可以查看本中心的情况
            condition = (Resource.c.kfzx == request.user._kfzx_) & condition
        else:                   #如果是管理员，只可以查看所属系统的情况
            system_ids = request.user.users_systems.ids()
            if system_ids:
                condition = (Resource.c.system.in_(system_ids)) & condition
            else:
                condition = (Resource.c.system != Resource.c.system) & condition
    elif request.user.department == '3':    #测试中心可以看对应的中心信息
        condition = (Resource.c.kfzx == request.user._kfzx_) & condition
        
    if c.get('kfzx'):
        condition = (Resource.c.kfzx == int(c['kfzx'])) & condition
    if c.get('system'):
        condition = (Resource.c.system == int(c['system'])) & condition
    if c.get('login_name'):
        condition = (Resource.c.user == Human.c.login_name) & (Human.c.login_name.like('%'+c['login_name']+'%')) & condition
    if c.get('name'):
        condition = (Resource.c.user == Human.c.login_name) & (Human.c.name.like('%'+c['name']+'%')) & condition
    if c.get('type'):
        condition = (Resource.c.type == c['type']) & condition
    if c.get('department'):
        condition = (Resource.c.user == Human.c.login_name) & (Department.c.code == Human.c.department) & (Department.c.name.like('%'+c['department']+'%')) & condition
    
    pageno = int(request.POST.get('page', 1)) - 1
    rows_per_page = int(request.POST.get('rows', 10))
    
    def name(value, obj):
        return u'<a href="/resource/usage/resource/view/%d">%s</a>' % (obj.id, obj.user.name)
    
    def login_name(value, obj):
        return obj.user.login_name
    
    def type(value, obj):
        return obj.user.get_display_value('type')
    
    def is_selfdev(value, obj):
        if value:
            return '<div class="ui-icon ui-icon-check"></div>'
        else:
            return '<div class="ui-icon ui-icon-closethick"></div>'
    
#    def action(value, obj):
#        return """<a href="%(href1)s">%(a1)s</a>&nbsp;<a href="%(href2)s">%(a2)s</a>""" % {
#            'href1':url_for(resource_usage_edit, id=obj.id),
#            'a1':'调整',
#            'href2':url_for(resource_usage_clone, id=obj.id),
#            'a2':'复制'}
    
    def department(value, obj):
        return u'<span title="机构编号:%s">%s</span>' % (obj.user.department.code, obj.user.department.name)
    
    fields_convert_map = {'department':department, 'name':name, 'login_name':login_name,
        'type':type, 'is_selfdev':is_selfdev,
    }
    
    _id = '%s_table' % model
    view =  ListView(model, condition=condition, rows_per_page=rows_per_page, 
        pageno=pageno, id=_id, order_by=(Resource.c.kfzx.asc(), Resource.c.system.asc(), Resource.c.user.asc()),
        fields_convert_map=fields_convert_map)
    
    if 'download' in request.GET:
        def download_name(value, obj):
            return obj.user.name
        def download_department(value, obj):
            return u'%s(%s)' % (obj.user.department.name, obj.user.department.code)
        
        return view.download('humans.xls', action='download', timeout=0, 
            fields_convert_map={'department':download_department, 'name':download_name, 'login_name':login_name,
            'type':type})
    else:
        data = {'query_form':query_view.form}
        if request.user.is_superuser:
            data['download'] = True
        return g_views.generic_list(model, get_url, template='resource_usage_list.html', 
            view=view, data=data, json_result=True)

@expose('/resource/usage/edit')
def resource_usage_edit():
    from uliweb.utils.generic import ReferenceSelectField
    from uliweb.orm import get_model
    from uliweb.utils.generic import ListView

    System = get_model('system')

    query = None
    if request.user.department == '2':
        if request.user.is_gm:
            query = System.filter((System.c.kfzx==request.user._kfzx_) | (System.c.sys_type == '5'))
        else:
            query = System.filter(System.users.in_(request.user.id) | (System.c.sys_type == '5'))
    system = ReferenceSelectField('system', label='系统', query=query, name='system', id='system')

    resource_table =  ListView('resource')
    fields = ('name', 'login_name', 'type', 'assigned', 'department')
    human_table = ListView('human', fields=fields)
    
    query_view = create_human_query(url_for(resource_humans))
    query_view.run()
    return {'system':system.html(), 
        'resource_table':resource_table, 
        'ready_table':human_table, 
        'query_form':query_view.form,
        }

@expose('/resource/usage/remove')
def resource_usage_remove():
    from uliweb.orm import get_model
    import datetime
    
    Resource = get_model('resource')
    Human = get_model('human')
    
    #获得resource后，先删除，然后判断是否还存在user信息，如果没有，则Human对应的assigned应置为False
    ids = request.POST.getlist('ids[]', int)
    total = 0
    error = 0
    success = True
    for id in ids:
        obj = Resource.get(id)
        user = obj._user_
        message = '未找到记录！'
        if obj:
#            obj.delete()
            #不真正删除，而是记录删除时间，用于工作强度统计
            #应在下个月跑完资源报表后删除
            #当只有一条记录时，置删除标志
            #如果有多条记录，则直接删除
            count = Resource.filter(Resource.c.user == user).count()
            if count == 1:
                obj.delete_flag = True
                obj.delete_date = datetime.datetime.now()
                obj.save()
            else:
                obj.delete()
                
            message = '处理成功！'
            total += 1
            count = Resource.filter(Resource.c.user == user).filter(Resource.c.delete_flag==False).count()
            human = Human.get(Human.c.login_name == user)
            if human:
                human.assigned = count > 0
                human.save()
        else:
            error += 1
    if error:
        error_msg = '，其中有%d条信息未找到' % error
    else:
        error_msg = ''
    return json({'success':success, 'data':'处理成功，一共删除 %d 条记录' % total+error_msg})
        
@expose('/resource/usage/resource')
def resource_usage_resource():
    from uliweb.orm import get_model
    from uliweb.utils.generic import ListView

    def name(value, obj):
        return obj.user.name
    
    def login_name(value, obj):
        return obj.user.login_name
    
    def type(value, obj):
        return obj.user.get_display_value('type')
    
    def department(value, obj):
        return u'<span title="机构编号:%s">%s</span>' % (obj.user.department.code, obj.user.department.name)

    def is_selfdev(value, obj):
        if value:
            return '<div class="ui-icon ui-icon-check"></div>'
        else:
            return '<div class="ui-icon ui-icon-closethick"></div>'
    
    fields_convert_map = {'department':department, 'name':name, 'login_name':login_name,
        'type':type, 'is_selfdev':is_selfdev,
    }
    
    Resource = get_model('resource')
    
    pageno = int(request.POST.get('page', 1)) - 1
    rows_per_page = int(request.POST.get('rows', 10))
    
    system = request.POST.get('system', -1) or 0
    condition = (Resource.c.system == system) & (Resource.c.delete_flag == False)
    view =  ListView('resource', condition=condition, rows_per_page=rows_per_page, 
        pageno=pageno, fields_convert_map=fields_convert_map, order_by=[Resource.c.type.desc(), Resource.c.user])
    return json(view.json())

@expose('/resource/usage/resource/edit/<id>')
def resource_usage_resource_edit(id):
    from uliweb.utils.generic import EditView
    from uliweb.orm import get_model
    from forms import ResourceEditForm
    
    Resource = get_model('resource')
    System = get_model('system')
    obj = Resource.get(int(id))
    
    def pre_save(obj, data):
        if not data.get('is_selfdev'):
            data['is_selfdev'] = False
    
    def post_created_form(fcls, model, obj):
        query = None
        if request.user.department == '2':
            if request.user.is_gm:
                query = System.filter((System.c.kfzx==request.user._kfzx_) | (System.c.sys_type == '5'))
            else:
                query = System.filter(System.users.in_(request.user.id) | (System.c.sys_type == '5'))
        fcls.system.query = query
        
    if request.user.users_systems.has(obj._system_) or (request.user.is_gm and request.user._kfzx_ == obj.system._kfzx_) or (obj.system.sys_type=='5'):
        view = EditView(Resource, obj=obj, form_cls=ResourceEditForm,
            post_created_form=post_created_form, pre_save=pre_save,
            form_args={'action':request.path, 'html_attrs':{'id':'edit_usage_form'}},)
        result = view.run(json_result=True)
        return result
    else:
        return error('你无权编辑此资源！')
    
@expose('/resource/usage/resource/view/<int:id>')
def resource_usage_resource_view(id):
    from uliweb.orm import get_model
    
    Resource = get_model('resource')
    obj = Resource.get(int(id))
    return resource_view(obj)

@expose('/resource/usage/resource/view/loginname/<loginname>')
def resource_usage_resource_view_loginname(loginname):
    from uliweb.orm import get_model
    
    Resource = get_model('resource')
    obj = Resource.get(Resource.c.user==loginname)
    
    response.template = 'resource_usage_resource_view.html'
    return resource_view(obj)

def resource_view(obj):
    from uliweb.utils.generic import DetailView
    from uliweb.orm import get_model
    
    Resource = get_model('resource')
    HumanHis = get_model('humanhis')
    
    def department(value, obj):
        return u'<span title="机构编号:%s">%s</span>' % (value, obj.user.department.name)
    
    fields_convert_map = {'department':department}
    view = DetailView(Resource, obj=obj, fields_convert_map=fields_convert_map)
    result = view.run()
    resources = Resource.filter(Resource.c.user==obj._user_)
    humans_his = HumanHis.filter(HumanHis.c.user==obj._user_)
    result['resources'] = resources
    result['humans_his'] = humans_his
    
    def display_change(row):
        from uliweb import settings
        import pickle
        from uliweb.orm import get_model
        from uliweb.utils.common import get_choice

        Resource = get_model('resource')
        System = get_model('system')
        
        def get_system_name(sys_id):
            return System.get(sys_id).name
        
        def get_role_name(role_id):
            return unicode(get_choice(settings.get_var('PARA/RESOURCE_ROLE', {}), role_id), 'utf-8')
        
        msg = []
        if row.changed_value:
            changed_value = pickle.loads(row.changed_value)
        else:
            changed_value = {}
        if row.old_value:
            old_value = pickle.loads(row.old_value)
        else:
            old_value = {}
        txt = ''
        if row.modify_flag == '1':
            txt = u'分配给 [%s] 系统' % get_system_name(changed_value['system'])
            if changed_value['role']:
                txt += u'，指定角色为 [%s]' % get_role_name(changed_value['role'])
        elif row.modify_flag == '3':
            txt = u'调离 [%s] 系统' % get_system_name(old_value['system'])
        else:
            if 'system' in changed_value:
                txt += u'从 [%s] 系统调整到 [%s] 系统' % (get_system_name(old_value['system']), get_system_name(changed_value['system']))
            if 'role' in changed_value:
                old_role = get_role_name(old_value['role'])
                if old_role:
                    old_role_msg = u'从 [%s] ' % old_role
                else:
                    old_role_msg = ''
                txt += u'角色%s调整为 [%s]' % (old_role_msg, get_role_name(changed_value['role']))
        return txt
    result['display_change'] = display_change
    return result

@expose('/resource/usage/human')
def resource_usage_human():
    from uliweb.utils.generic import ReferenceSelectField
    from uliweb.orm import get_model
    from uliweb.utils.generic import ListView
    from uliweb import orm
    import generic.views as g_views
    from sqlalchemy.sql import and_, or_

    Department = orm.get_model('department')
    Human = orm.get_model('human')
    
    query_view = create_human_query(url_for(resource_humans))
    c = query_view.run()

    condition = and_(
        (Human.c.delete_flag == False),
        (Department.c.code == Human.c.department),
        or_(
            (Human.c.type=='3') & (Department.c.kfzx == request.user._kfzx_),
            Human.c.type!='3',
            ),
    )
    
    if c.get('department'):
        condition = (Department.c.code == Human.c.department) & (Department.c.name.like('%'+c['department']+'%')) & condition
    if c.get('name'):
        condition = (Human.c.name.like('%'+c['name']+'%')) & condition
    if c.get('login_name'):
        condition = (Human.c.login_name.like('%'+c['login_name']+'%')) & condition
    if c.get('type'):
        condition = (Human.c.type == c['type']) & condition
        if c['type'] == '3':
            condition = (Department.c.code == Human.c.department) & (Department.c.kfzx == request.user._kfzx_) & condition
    if c.get('assigned'):
        if c['assigned'] == '1':
            condition = (Human.c.assigned) & condition
        else:
            condition = (~Human.c.assigned) & condition
    
#    condition = (~ Human.c.assigned) & condition

    pageno = int(request.POST.get('page', 1)) - 1
    rows_per_page = int(request.POST.get('rows', 10))
    
    def department(value, obj):
        return u'<span title="机构编号:%s">%s</span>' % (value, obj.department.name)

    def assigned(value, obj):
        if value:
            return '<div class="ui-icon ui-icon-check"></div>'
        else:
            return '<div class="ui-icon ui-icon-closethick"></div>'

    view =  ListView(Human, condition=condition, rows_per_page=rows_per_page, 
        pageno=pageno, order_by=(Human.c.type.desc(), Human.c.department.asc(), Human.c.login_name.asc()))
    view.fields_convert_map = {'department':department, 'assigned':assigned}
    return json(view.json())

@expose('/resource/usage/add')
def resource_usage_add():
    from uliweb.orm import get_model, do_
    from sqlalchemy.sql import select, func
    from decimal import Decimal
    
    ids = request.POST.getlist('ids[]', int)
    system = int(request.POST.get('system', -1))
    
    if ids:
        Resource = get_model('resource')
        Human = get_model('human')
        System = get_model('system')
        
        sys = System.get(system)
        if not sys:
            return json({'success':False, 'data':'系统不存在'})
        else:
            kfzx = sys._kfzx_
        error = 0
        total = 0
        for i in ids:
            human = Human.get(i)
            if human:
                human.assigned = True
                human.save()
                Resource.filter(Resource.c.user==human.login_name).filter(Resource.c.delete_flag==True).remove()
                r = Resource.get((Resource.c.user == human.login_name) & (Resource.c.system == system))
                if r:
                    error += 1
                else:
                    r = do_(select([func.sum(Resource.c.workload)], (Resource.c.user == human.login_name)))
                    sum = list(r)[0][0] or Decimal('0.0')
                    workload = Decimal('1.0') - sum
                    r = Resource(user=human, kfzx=kfzx, workload=workload, type=human.type, system=system, is_selfdev=True)
                    r.save()
                total += 1
        if error:
            error_msg = '，其中有重复记录 %d 条' % error
        else:
            error_msg = ''
        return json({'success':True, 'data':'成功处理 %d 条记录' % total + error_msg})

def create_human_query(url):
    from uliweb.utils.generic import QueryView
    from uliweb.form import SelectField, UnicodeField, IntField, StringField
    from query.forms import QueryForm
    from uliweb.utils.generic import ReferenceSelectField
    
    type = SelectField(label='类型', choices=settings.get_var('PARA/HUMAN_TYPE'))
    assigned = SelectField(label='是否已分配', choices=settings.get_var('PARA/YES_NO'))
    department = UnicodeField(name='department', label='所属机构')
    kfzx = ReferenceSelectField('kfzx', label='相关开发中心')
    workload = IntField('workload',)
    flag = StringField(name='flag')
    
    fields = ('name', 'login_name', ('assigned', assigned), ('type', type), 
            ('department', department), ('kfzx',kfzx), ('workload',workload),('flag',flag)) 
    layout = [('assigned', 'type', 'department'), ('name', 'login_name')]
    query = QueryView('human', ok_url=url, fields=fields, layout=layout, form_cls=QueryForm)
    return query

@expose('/resource/humans')
@expose('/resource/humans/list')
def resource_humans():
    from uliweb.utils.generic import ListView
    from uliweb import orm
    import generic.views as g_views
    from sqlalchemy.sql import select,func
    from sqlalchemy.sql import and_,or_,exists
    from uliweb.core.html import Tag
    
    
    get_url = g_views.get_url('/resource/humans')

    model = 'human'

    Department = orm.get_model('department')
    Human = orm.get_model('human')
    zx = orm.get_model('kfzx')
    resource = orm.get_model('resource')
    
    query_view = create_human_query(url_for(resource_humans))
    c = query_view.run()
    condition = Human.c.delete_flag == False
    query = None
    if c.get('department'):
        condition = (Department.c.code == Human.c.department) & (Department.c.name.like('%'+c['department']+'%')) & condition
    if c.get('name'):
        condition = (Human.c.name.like('%'+c['name']+'%')) & condition
    if c.get('login_name'):
        condition = (Human.c.login_name.like('%'+c['login_name']+'%')) & condition
    if c.get('type'):
        condition = (Human.c.type == c['type']) & condition
    if c.get('assigned') == '1':
        condition = (Human.c.assigned) & condition
    elif c.get('assigned') == '0':
        condition = (~Human.c.assigned) & condition
    if c.get('kfzx'):
        if c['kfzx'] == 99:
            condition = (Department.c.code == Human.c.department) & (Department.c.kfzx != None) & condition
        elif c['kfzx'] == 98:
            condition = (Department.c.code == Human.c.department) & (Department.c.kfzx == 1) & condition        
        else:
            condition = (Department.c.code == Human.c.department) & (Department.c.kfzx == int(c['kfzx'])) & condition
    if c.get('workload'):
        a = select([resource.c.user,],resource.c.user == Human.c.login_name)\
            .group_by(resource.c.user).having(func.sum(resource.c.workload)<1)
        condition = or_(~Human.c.assigned,exists(a)) & condition
    
    pageno = int(request.values.get('page', 1)) - 1
    rows_per_page = int(request.values.get('rows', settings.get_var('PARA/ROWS_PER_PAGE', 10)))
    
    def department(value, obj):
        return u'<span title="机构编号:%s">%s</span>' % (value, obj.department.name)
    
    def assigned(value, obj):
        if value:
            return '<div class="ui-icon ui-icon-check"></div>'
        else:
            return '<div class="ui-icon ui-icon-closethick"></div>'

    def workload_total(value, obj):
        sql_bg = select([resource.c.user,func.sum(resource.c.workload),],
            and_(resource.c.user==obj.login_name)).group_by(resource.c.user)
        
        sql_bg_rs = orm.do_(sql_bg)
        workload = 0
        for row in sql_bg_rs:
            user,wl = row
            if user==obj.login_name:
                workload = wl
        return workload
    def teams(value, obj):
        name=''
        if obj.teams:
            for row in obj.teams.all():
                name=name+str(Tag('a', row.name, href='/resource/teams/%d' % row.id))
            return name
        else:
            return
    def duties(value, obj):
        if obj.duties:
            return str(Tag('a', obj.duties.name, href='/resource/duties/%d' % obj.id))
        return
    def position(value, obj):
        if obj.position:
            return str(Tag('a', obj.position.name, href='/resource/position/%d' % obj.id))
        return
    
    _id = '%s_table' % model
#    view =  ListView(model, condition=condition, rows_per_page=rows_per_page, 
#        pageno=pageno, id=_id, order_by=(Human.c.department.asc(), Human.c.type.asc(), Human.c.login_name.asc()))
    if 'download' in request.GET:
        def teams(value, obj):
            name=u''
            if obj.teams:
                for row in obj.teams.all():
                    name=name+row.name
                return name
            else:
                return
        def duties(value, obj):
            if obj.duties:
                return obj.duties.name
            else:
                return
        def position(value, obj):
            if obj.position:
                return obj.position.name
            else:
                return
        fields = ('name','login_name','type','teams','duties','position','enter_date','telphone','mobile','email','assigned','workload_total','department',)
        view =  ListView(model, condition=condition, rows_per_page=rows_per_page, 
            pageno=pageno, id=_id,fields=fields, order_by=(Human.c.department.asc(), Human.c.type.asc(), Human.c.login_name.asc()))
        
        view.fields_convert_map = { 'teams':teams, 'duties':duties, 'position':position}
        return view.download('humans.xls', action='download', timeout=0)
    else:
        if c.get('flag'):
            data = {'query_form':''}
        else:
            data = {'query_form':query_view.form}
        if request.user.is_superuser:
            data['download'] = True
        view =  ListView(model, condition=condition, rows_per_page=rows_per_page, 
            pageno=pageno, id=_id, order_by=(Human.c.department.asc(), Human.c.type.asc(), Human.c.login_name.asc()))
        
        view.fields_convert_map = {'department':department,'workload_total':workload_total, 'assigned':assigned, 'teams':teams, 'duties':duties, 'position':position}
        return g_views.generic_list(model, get_url, template='resource_humans_list.html', 
            view=view, data=data, json_result=True)

class UploadHumanView(AddView):
    def on_success(self, data, json_result=False):
        import csv
        from uliweb.orm import get_model
        from uliweb.utils.common import log
        from uliweb import request
        import datetime
        from datetime import date
        import time
        
        Human = get_model('human')
        Department = get_model('department')
        Team = get_model('team')
        Duties = get_model('duties')
        Position = get_model('position')
        num = 0
        error_num = 0
        
        try:
#            fff=csv.reader(data['file']['file'])
#            fff.next()
            for line in csv.reader(data['file']['file']):
                num += 1
                if num == 1:
                    continue
                name,login_name,type,teams,duties,position,enter_date,telphone,mobile,email,assigned,workload_total,department = line
                login_name = unicode(login_name.strip(), 'gbk')
                if has_role(request.user,'kfzx_gm'):
                    team_dic = {}
                    duties_dic = {}
                    position_dic = {}
                    for row_team in Team.filter(Team.c.kfzx == request.user._kfzx_):
                        team_dic.setdefault(row_team.name,row_team.id)
                    for row_team in Duties.filter():
                        duties_dic.setdefault(row_team.name,row_team.id)
                    for row_team in Position.filter(Position.c.kfzx == request.user._kfzx_):
                        position_dic.setdefault(row_team.name,row_team.id)
                    
                    row = Human.get(Human.c.login_name == login_name)
                    if row.department and row.department._kfzx_ == request.user._kfzx_:
                        try:
                            teams = unicode(teams.strip(), 'gbk')
                            duties = unicode(duties.strip(), 'gbk')
                            position = unicode(position.strip(), 'gbk')
                            telphone = unicode(telphone.strip(), 'gbk')
                            mobile = unicode(mobile.strip(), 'gbk')
                            email = unicode(email.strip(), 'gbk')
                        except UnicodeDecodeError, e:
                            log.error("团队、职务、岗位、电话、手机或email有误，请修改后重新导入！:%d,%s" % (num, ','.join(line)))
                            flash("团队、职务、岗位、电话、手机或email有误，请修改后重新导入！:%d,%s" % (num, ','.join(line)))
                            return redirect(self.ok_url)
#                        enter_date = enter_date.replace('-', '') 
#                        enter_date_t = enter_date.split()
#                        i=0
#                        year=''
#                        month = ''
#                        str_date = ''
#                        for xxx in enter_date_t:
#                            i+=1
#                            if i<5:
#                                year+=xxx
#                            if i>4 and i<7:
#                                month +=xxx
#                            if i>6 and i<9:
#                                str_date +=xxx
#                        datestr=year+'-'+month+'-'+str_date
                        datestr=enter_date
                        try:
                            row.enter_date = datetime.date(*time.strptime(datestr, "%Y-%m-%d")[:3])
                        except UnicodeDecodeError, e:
                            log.exception(e)
                            flash('处理过程有问题，数据行号为[%d],入行时间有错误，请处理后重新导入！' % num)
                            return redirect(self.ok_url)
                        #数值转换
#                        print teams,team_dic[teams],team_dic
                        row.teams=[team_dic[teams]]
                        row.duties=duties_dic[duties]
                        row.position=position_dic[position]
                        row.telphone=telphone
                        row.mobile=mobile
                        row.email=email
                        
                        row.save()
                elif request.user.is_superuser:
                    team_dic = {}
                    duties_dic = {}
                    position_dic = {}
                    for row_team in Team.all():
                        team_dic.setdefault(row_team.name,row_team.id)
                    for row_team in Duties.all():
                        duties_dic.setdefault(row_team.name,row_team.id)
                    for row_team in Position.all():
                        position_dic.setdefault(row_team.name,row_team.id)
                    
                    row = Human.get(Human.c.login_name == login_name)
#                    if row.department and row.department._kfzx_ == request.user._kfzx_:
                    try:
                        teams = unicode(teams.strip(), 'gbk')
                        duties = unicode(duties.strip(), 'gbk')
                        position = unicode(position.strip(), 'gbk')
                        telphone = unicode(telphone.strip(), 'gbk')
                        mobile = unicode(mobile.strip(), 'gbk')
                        email = unicode(email.strip(), 'gbk')
                    except UnicodeDecodeError, e:
                        log.error("团队、职务、岗位、电话、手机或email有误，请修改后重新导入！:%d,%s" % (num, ','.join(line)))
                        flash("团队、职务、岗位、电话、手机或email有误，请修改后重新导入！:%d,%s" % (num, ','.join(line)))
                        return redirect(self.ok_url)
#                    enter_date = enter_date.replace('-', '') 
#                    enter_date_t = enter_date.split()
#                    i=0
#                    year=''
#                    month = ''
#                    str_date = ''
#                    for xxx in enter_date_t:
#                        i+=1
#                        if i<5:
#                            year+=xxx
#                        if i>4 and i<7:
#                            month +=xxx
#                        if i>6 and i<9:
#                            str_date +=xxx
#                    datestr=year+'-'+month+'-'+str_date
                    datestr=enter_date

                    if row:
                        try:
                            row.enter_date = datetime.date(*time.strptime(datestr, "%Y-%m-%d")[:3])
                        except UnicodeDecodeError, e:
                            log.exception(e)
                            flash('处理过程有问题，数据行号为[%d],入行时间有错误，请处理后重新导入！' % num)
                            return redirect(self.ok_url)
                        #数值转换
#                        print teams,team_dic[teams],team_dic
                        row.teams=[team_dic[teams]]
                        row.duties=duties_dic[duties]
                        row.position=position_dic[position]
                        row.telphone=telphone
                        row.mobile=mobile
                        row.email=email
                        
    #                    row.save()
                        if not login_name or not name or not type or not department:
                            log.error("Error human info:%d,%s" % (num, ','.join(line)))
                            error_num += 1
                            continue
                        try:
                            name = unicode(name.strip(), 'gbk')
#                            login_name = unicode(login_name.strip(), 'gbk')
#                            department = unicode(department.strip(), 'gbk')
                        except UnicodeDecodeError, e:
                            log.error("Error human info:%d,%s" % (num, ','.join(line)))
                            error_num += 1
                            continue
                            
                        #检查department信息
#                        if not Department.get(Department.c.name == department):
#                            log.error("Can't find the department:%d,%s" % (num, ','.join(line)))
#                            error_num += 1
#                            continue
#                        type = unicode(type.strip(), 'gbk')

                    else:#超级用户新增分行人员处理过程，用户名、登录名；类型、部门和是否分配需要填写代码，电话、手机或email等分行需填写。
#                        type = unicode(type.strip(), 'gbk')
                        name = unicode(name.strip(), 'gbk')
#                        department = unicode(department.strip(), 'gbk')
                        
                        if not Department.get(Department.c.code == department):
                            log.error("Can't find the department:%d,%s" % (num, ','.join(line)))
                            error_num += 1
                            continue
                        
                        row = Human(name=name, type=type, login_name=login_name, department=department,telphone=telphone,mobile=mobile,email=email,assigned=assigned)
                    row.save()
                else:
                   flash('你不是超级用户或中心管理员，无法导入数据！') 
            
            if error_num > 0:
                msg = '存在%d条出错记录，请检查日志！' % error_num
            else:
                msg = ''
            flash('导入成功，共导入 %d 条记录。%s' % (num, msg))
            return redirect(self.ok_url)
        except Exception, e:
            log.exception(e)
            flash('处理过程有问题，数据行号为[%d],请与程序员联系' % num)
            return redirect(self.ok_url)

@expose('/resource/humans/upload')
def resource_humans_upload():
    from forms import UploadForm
    
    if request.user.is_superuser or has_role(request.user,'kfzx_gm'):
        view = UploadHumanView('human', url_for(resource_humans), fields=(), 
            form_cls=UploadForm)
        return view.run()
    else:
        flash('你不是超级用户或中心管理员，无法导入数据！')
        return redirect(url_for(resource_humans))
    
#@expose('/resource/humans/sync')
#def resource_humans_sync():
#    from uliweb.orm import get_model
#    import decimal
#    
#    if request.user.is_superuser:
#        Human = get_model('human')
#        Resource = get_model('resource')
#        Department = get_model('department')
#        num = 0
#        for row in Human.filter(Human.c.department == Department.c.code).filter(Department.c.kfzx!=None):
#            for obj in Resource.filter(Resource.c.user == row.login_name):
#                obj.kfzx = row.department._kfzx_
#                obj.save()
#            else:
#                obj = Resource(user=row, kfzx=row.department._kfzx_, workload=decimal.Decimal('1.0'), type=row.type)
#                obj.save()
#            num += 1
#        flash('处理完毕，一共处理%d条！' % num)
#        
#    else:
#        flash('你不是超级用户，无法执行此功能！')
#    return redirect(url_for(resource_humans))
#    
def create_department_query(url):
    from uliweb.utils.generic import QueryView
    from uliweb.form import SelectField
    
    type = SelectField(label='机构类型', choices=settings.get_var('PARA/DEPARTMENT_TYPE'))
    fields = ('code', ('type', type), 'name') 
    query = QueryView('department', ok_url=url, fields=fields)
    return query

@expose('/resource/departments')
@expose('/resource/departments/list')
def resource_departments():
    from uliweb.utils.generic import ListView
    from uliweb import orm
    import generic.views as g_views
    from uliweb.core.html import Tag
    
    get_url = g_views.get_url('/resource/departments')
    
    model = 'department'
    
    Department = orm.get_model(model)
    
    query_view = create_department_query(url_for(resource_departments))
    c = query_view.run()
    
    condition = Department.c.delete_flag == False
    query = None
    if c.get('code'):
        condition = (Department.c.code.like('%'+c['code']+'%')) & condition
    if c.get('name'):
        condition = (Department.c.name.like('%'+c['name']+'%')) & condition
    if c.get('type'):
        condition = (Department.c.type == c['type']) & condition
    
    pageno = int(request.values.get('page', 1)) - 1
    rows_per_page = int(request.values.get('rows', settings.get_var('PARA/ROWS_PER_PAGE', 10)))
    
    def action(value, obj):
        return str(Tag('a', '编辑', href=url_for(resource_department_edit, id=obj.id)))
    
    if request.user.is_superuser:
        fields = [
                    {'name':'code', 'width':200},
                    'type',
                    'kfzx',
                    {'name':'name', 'width':400},
                    {'name':'action', 'verbose_name':'操作'},
                ]
    else:
        fields = [
                    {'name':'code', 'width':200},
                    'type',
                    'kfzx',
                    {'name':'name', 'width':400},
                ]
        
    _id = '%s_table' % model
    view =  ListView(model, condition=condition, rows_per_page=rows_per_page, 
        pageno=pageno, id=_id, fields=fields)
    
    if 'download' in request.GET:
        return view.download('departments.xls', action='download', timeout=0)
    else:
        data = {'query_form':query_view.form}
        if request.user.is_superuser:
            data['download'] = True
        view.fields_convert_map = {'action':action}
        return g_views.generic_list(model, get_url, template='resource_departments_list.html', 
            view=view, data=data, json_result=True)

class UploadDepartmentView(AddView):
    department_type = '1'
    
    def on_success(self, data):
        import csv
        from uliweb.orm import get_model
        from uliweb.utils.common import log
        from uliweb.orm import Rollback
        
        Department = get_model('department')
        num = 0
        try:
            for line in csv.reader(data['file']['file']):
                num += 1
                if num == 1:
                    continue
                code, name = line
                if not code or not name:
                    continue
                code = unicode(code.strip(), 'gbk')
                name = unicode(name.strip(), 'gbk')
                row = Department.get(Department.c.code == code)
                if row:
                    row.name = name
                else:
                    row = Department(name=name, code=code, type=self.department_type)
                row.save()
            
            flash('导入成功，共导入 %d 条记录' % num)
            return redirect(self.ok_url)
        except Exception, e:
            log.exception(e)
            flash('处理过程有问题，行号为[%d]，请与程序员联系' % num)
            Rollback()
            return redirect(self.ok_url)

@expose('/resource/departments/upload/<type>')
def resource_departments_upload(type):
    from forms import UploadForm
    
    if type == 'ccb':
        UploadDepartmentView.department_type = '1'
        msg_type = '建行'
    else:
        UploadDepartmentView.department_type = '2'
        msg_type = '公司'
        
    if request.user.is_superuser:
        view = UploadDepartmentView('department', url_for(resource_departments), fields=(), 
            form_cls=UploadForm, template_data={'type':msg_type})
        return view.run()
    else:
        flash('你不是超级用户，无法导入数据！')
        return redirect(url_for(resource_departments))

@expose('/resource/department/<int:id>/edit')
def resource_department_edit(id):
    import generic.views as g_views
    from uliweb.utils.generic import EditView
    from uliweb.orm import get_model

    Department = get_model('department')
    obj = Department.get(int(id))
    view = EditView('department', url_for(resource_departments), obj=obj)
    if request.user.is_superuser:
        return g_views.generic_edit(layout='resource_layout.html', title=u'修改开发中心-%s' % obj.name, view=view)
    else:
        flash('你不是超级用户，无法编辑此机构！')
        return redirect(url_for(resource_departments))
    

@expose('/resourcehis/usage')
@expose('/resourcehis/usage/list')
def resourcehis_usage_list():
    from uliweb.utils.generic import ListView
    from uliweb import orm
    import generic.views as g_views
    from uliweb.core.html import Tag
   
    get_url = g_views.get_url('/resourcehis/usage/list')
    model = 'resourcehis'
    Department = orm.get_model('department')
    Human = orm.get_model('human')
    Resource = orm.get_model('resourcehis')
    query_view = create_usage_query(url_for(resource_usage))
    c = query_view.run()
    query = None
    condition = None
    if request.user.department == '2':
        if request.user.is_gm:  #如果是开发中心主管，则只可以查看本中心的情况
            condition = (Resource.c.kfzx == request.user._kfzx_)
        else:                   #如果是管理员，只可以查看所属系统的情况
            system_ids = request.user.users_systems.ids()
            if system_ids:
                condition = (Resource.c.system.in_(system_ids))
            else:
                condition = (Resource.c.system != Resource.c.system)
    elif request.user.department == '3':    #测试中心可以看对应的中心信息
        condition = (Resource.c.kfzx == request.user._kfzx_)
        
    if c.get('kfzx'):
        condition = (Resource.c.kfzx == int(c['kfzx'])) & condition
    if c.get('system'):
        condition = (Resource.c.system == int(c['system'])) & condition
    if c.get('login_name'):
        condition = (Resource.c.user == Human.c.login_name) & (Human.c.login_name.like('%'+c['login_name']+'%')) & condition
    if c.get('name'):
        condition = (Resource.c.user == Human.c.login_name) & (Human.c.name.like('%'+c['name']+'%')) & condition
    if c.get('type'):
        if c['type']=='1':            
            condition = (Resource.c.type.in_(['1','3'])) & condition
        if c['type']=='2':
            condition = (Resource.c.type.in_(['2'])) & condition            
    if c.get('department'):
        condition = (Resource.c.user == Human.c.login_name) & (Department.c.code == Human.c.department) & (Department.c.name.like('%'+c['department']+'%')) & condition
    if c.get('yearmon'):
        condition = (Resource.c.yearmon == c['yearmon']) & condition
    
    pageno = int(request.POST.get('page', 1)) - 1
    rows_per_page = int(request.POST.get('rows', 10))
    
    def name(value, obj):
        return u'<a href="/resource/usage/resource/view/loginname/%s">%s</a>' % (obj._user_, obj.user.name)
    
    def login_name(value, obj):
        return obj.user.login_name
    
    def type(value, obj):
        return obj.user.get_display_value('type')
    
    def action(value, obj):
        return """<a href="%(href1)s">%(a1)s</a>&nbsp;<a href="%(href2)s">%(a2)s</a>""" % {
             'href1':url_for(resource_usage_edit, id=obj.id),
             'a1':'调整',
             'href2':url_for(resource_usage_clone, id=obj.id),
             'a2':'复制'}
    
    def department(value, obj):
        return u'<span title="机构编号:%s">%s</span>' % (obj.user.department.code, obj.user.department.name)
    
    fields_convert_map = {'department':department, 'name':name, 'login_name':login_name,
        'type':type, 
    }
    
    _id = '%s_table' % model
    view =  ListView(model, condition=condition, rows_per_page=rows_per_page, 
        pageno=pageno, id=_id, order_by=(Resource.c.kfzx.asc(), Resource.c.system.asc(), Resource.c.user.asc()),
        fields_convert_map=fields_convert_map)
    
    if 'download' in request.GET:
        def download_name(value, obj):
            return obj.user.name
        def download_department(value, obj):
            return u'%s(%s)' % (obj.user.department.name, obj.user.department.code)
        
        return view.download('humans.xls', action='download', timeout=0, 
            fields_convert_map={'department':download_department, 'name':download_name, 'login_name':login_name,
            'type':type})
    else:
        data = {'query_form':''}
        if request.user.is_superuser:
            data['download'] = True
        return g_views.generic_list(model, get_url, template='resourcehis_usage_list.html', 
            view=view, data=data, json_result=True)
 